package app1.rapidsquare.com.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.Events;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.database.AgileEventsProvider;
import app1.rapidsquare.com.activity.R;

public class EventActivity extends AgileActivity {

    private ImageView mImageViewPhoto;
    private Button mButtonCheckIn;

    private TextView mTextViewDateTime, mTextViewTitle, mTextViewAuthor, mTextViewRoom, mTextViewAvg, mTextViewDetails, mTextViewCheckOut;
    private RatingBar mRatingBar;
    private Events event;
    private boolean isGoneToAuthentification;
    private TextView mTextViewInternetConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);
        setTitle(Utility.getUserSession(EventActivity.this).Code);
        mImageViewMenu.setImageResource(R.drawable.connect);

        mImageViewLogo.setImageResource(R.drawable.narrow_back);
        mImageViewLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
                finish();
            }
        });

        if (getIntent().hasExtra("EventData")) {
            event = (Events) getIntent().getExtras().getSerializable(
                    "EventData");
        }

        if (event == null) {
            onBackPressed();
            finish();
        }


        mTextViewDateTime = (TextView) findViewById(R.id.textViewEventDate);
        mImageViewPhoto = (ImageView) findViewById(R.id.imageViewLogo);
        mTextViewTitle = (TextView) findViewById(R.id.textViewEventTitle);
        mTextViewAuthor = (TextView) findViewById(R.id.textViewEventAuthor);
        mTextViewRoom = (TextView) findViewById(R.id.textViewEventRoom);
        mRatingBar = (RatingBar) findViewById(R.id.ratingBarEvent);
        mTextViewAvg = (TextView) findViewById(R.id.textViewEventAVG);
        mButtonCheckIn = (Button) findViewById(R.id.buttonEventCheckIn);
        mTextViewDetails = (TextView) findViewById(R.id.textViewEventDetails);
        mTextViewInternetConnection = (TextView) findViewById(R.id.textViewInternetConnection);
        mTextViewInternetConnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextViewInternetConnection.setVisibility(View.GONE);
            }
        });
        mButtonCheckIn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);

                    if (IsAuthentication()) {
                        try {
                            if (event.Id > 0) {
                                AgileEventsProvider eventsProvider = new AgileEventsProvider(EventActivity.this);
                                if (!eventsProvider.CheckEventToCheckIn(event)) {
                                    setUrl(Utility.CHECK_IN_EVENT_URL + "?usertoken="
                                            + Utility.getUserSession(EventActivity.this).UserToken + "&eventId="
                                            + event.Id + "&isCheckIn=true");
                                    setRequestMethodType(Utility.RequestMethodType.GET);
                                    SendRequest(true);
                                    Utility.AgileSyncUpdater(new AgileEventsProvider(EventActivity.this), null);
                                } else {
                                    Toast.makeText(EventActivity.this, getResources().getString(R.string.check_event_in_same_time), Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (Exception ex) {
                            Utility.Log("EventActivity -> mButtonCheckIn.setOnClickListener", ex);
                        }
                    } else
                        GoToAuthentification();
                } else
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
            }
        });
        mTextViewCheckOut = (TextView) findViewById(R.id.textViewCheckOut);
        mTextViewCheckOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);
                    if (IsAuthentication()) {
                        if (event.Id > 0) {
                            setUrl(Utility.CHECK_IN_EVENT_URL + "?usertoken="
                                    + Utility.getUserSession(EventActivity.this).UserToken + "&eventId="
                                    + event.Id + "&isCheckIn=false");
                            setRequestMethodType(Utility.RequestMethodType.GET);
                            SendRequest(true);
                            Utility.AgileSyncUpdater(new AgileEventsProvider(EventActivity.this), null);
                        }
                    } else
                        GoToAuthentification();
                } else
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        User userSession = Utility.getUserSession(EventActivity.this);
        if (userSession != null && !Utility.isNullOrEmpty(userSession.UserToken)) {
            mImageViewMenu.setOnClickListener(ConnectDialogOnClickListener);
            mImageViewMenu.setClickable(true);
            mImageViewMenu.setVisibility(View.VISIBLE);
        } else {
            mImageViewMenu.setOnClickListener(null);
            mImageViewMenu.setClickable(false);
            mImageViewMenu.setVisibility(View.GONE);
        }
        isGoneToAuthentification = false;
        LoadEvent();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isGoneToAuthentification = false;

        if (requestCode == Utility.SOCIAL_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK && data.hasExtra(Utility.SOCIAL_INTENT_DATA_NAME)) {
            setResult(RESULT_FIRST_USER, data);
            finish();
        }
    }

    @Override
    protected void getResponce(String result) {
        try {
            if (!Utility.isNullOrEmpty(result)) {
                JSONObject resultJsonObject = new JSONObject(result);
                if (resultJsonObject.has("Result")) {
                    String resultObject = resultJsonObject.getString("Result");

                    if (!resultObject.equals("The event is not Checked In by User")
                            && !resultObject
                            .equals("Unknown UserToken or Invalid Event Id")
                            && !resultObject.equals("Error is initialization")
                            && !resultObject.equals("Unknown User")
                            && !resultObject.equals("Waiting")
                            && !resultObject.equals("Confirm")
                            && !resultObject.equals("Cancel")
                            && !resultObject.equals("Already Added")
                            && !resultObject.equals("Cannot Add Yourself")) {

                        Events deserializeEvent = Utility.Deserialize(Events.class, resultObject);

                        if (event != null) {

                            event.IsCheckIn = deserializeEvent.IsCheckIn;
                            event.AvgRating = deserializeEvent.AvgRating;
                            event.UserRating = deserializeEvent.UserRating;

                            AgileEventsProvider eventsProvider = new AgileEventsProvider(EventActivity.this);
                            eventsProvider.CheckInEvent(event);
                            Utility.AgileSyncUpdater(eventsProvider, null);

                            LoadEvent();

                            setResult(RESULT_OK,
                                    new Intent().putExtra("EventData", event));

                        }
                    }
                    if (!Utility.isNullOrEmpty(resultObject)
                            && (resultObject.equals("Unknown User")
                            || resultObject.equals("Waiting")
                            || resultObject.equals("Confirm")
                            || resultObject.equals("Cancel")
                            || resultObject.equals("Already Added") || resultObject
                            .equals("Cannot Add Yourself"))) {

                        if (resultObject.equals("Waiting"))
                            resultObject = "Your request is sending";

                        Toast.makeText(EventActivity.this, resultObject,
                                Toast.LENGTH_SHORT).show();

                    }
                }
            }
        } catch (JSONException e) {
            Utility.Log("Welcome Activity error conver json to object ", e);
        }
    }

    private synchronized void GoToAuthentification() {
        if (!isGoneToAuthentification) {
            Intent intent = new Intent(EventActivity.this, SocialActivity.class);
            startActivityForResult(intent, Utility.SOCIAL_ACTIVITY_REQUEST_CODE);
            isGoneToAuthentification = true;
        }
    }

    private void LoadEvent() {

        if (event.IsCheckIn) {
            mButtonCheckIn.setVisibility(View.GONE);
            mTextViewAvg.setVisibility(View.GONE);
            mTextViewCheckOut.setVisibility(View.VISIBLE);
        } else {
            mButtonCheckIn.setVisibility(View.VISIBLE);
            mTextViewCheckOut.setVisibility(View.GONE);
            mTextViewAvg.setVisibility(View.GONE);
        }

        Calendar startDate = Utility.getNYCDate();
        startDate.setTime(event.StartTime);

        Calendar endDate = Utility.getNYCDate();
        endDate.setTime(event.EndTime);

        if (Utility.getNYCDate().compareTo(startDate) > 0) {
            mButtonCheckIn.setVisibility(View.GONE);
            mTextViewCheckOut.setVisibility(View.GONE);
            mTextViewAvg.setVisibility(View.VISIBLE);
            mRatingBar.setEnabled(true);
        } else {
            if (event.IsCheckIn
                    && Utility.getNYCDate().compareTo(startDate) < 0) {
                mTextViewCheckOut.setVisibility(View.VISIBLE);
                mButtonCheckIn.setVisibility(View.GONE);
            }
            mTextViewAvg.setVisibility(View.GONE);
            mRatingBar.setEnabled(false);
        }
        if (!Utility.isNullOrEmpty(event.AuthorImageUrl)) {
            Picasso picasso = Picasso.with(EventActivity.this);
            picasso.load(event.AuthorImageUrl)
                    .placeholder(R.drawable.agile_icon)
                    .error(R.drawable.agile_icon)
                    .resizeDimen(R.dimen.image_size,
                            R.dimen.image_size).centerInside()
                    .into(mImageViewPhoto);
        }

        if (event.UserRating != 0.0)
            mRatingBar.setRating(Float.valueOf(String.valueOf(event.UserRating)));

        mRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating,
                                        boolean fromUser) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);
                    if (IsAuthentication() && event.Id > 0) {
                        setUrl(Utility.CHECK_IN_EVENT_URL + "?usertoken="
                                + Utility.getUserSession(EventActivity.this).UserToken + "&eventId="
                                + event.Id + "&isCheckIn=true");
                        setRequestMethodType(Utility.RequestMethodType.GET);
                        SendRequest(true);

                        setUrl(Utility.RATING_EVENT_URL + "?usertoken="
                                + Utility.getUserSession(EventActivity.this).UserToken + "&eventId="
                                + event.Id + "&ratingValue=" + rating);
                        setRequestMethodType(Utility.RequestMethodType.GET);
                        SendRequest(true);
                        Utility.AgileSyncUpdater(new AgileEventsProvider(EventActivity.this), null);
                    } else {
                        GoToAuthentification();
                    }
                } else {
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
                }
            }
        });

        mTextViewAuthor.setText(event.Author);


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));


        mTextViewDateTime.setText(simpleDateFormat.format(startDate.getTime()) + " - "
                + simpleDateFormat.format(endDate.getTime()));

        mTextViewAvg.setText(getResources().getString(R.string.overall_rating) + " " + new DecimalFormat("##.##").format(event.AvgRating));

        mTextViewRoom.setText(event.Room);

        mTextViewTitle.setText(event.Topic);
        mTextViewDetails.setText(event.Introduction);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("CurrentEvent", event);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null
                && savedInstanceState.containsKey("CurrentEvent"))
            event = (Events) savedInstanceState.getSerializable("CurrentEvent");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_OK, new Intent().putExtra("EventData", event));
        finish();
    }
}
